package com.own.component.store.local.method;

import com.own.component.store.core.method.base.BaseStore;
import com.own.component.store.core.property.LocalStoreProperty;
import com.own.component.store.local.method.base.BaseScheduler;
import com.own.component.store.local.method.state.StoreState;

import java.time.Duration;
import java.util.Set;

/**
 * DefaultBaseStoreMethod
 *
 * @author chenxueli
 * @date 2024-05-15 11:34:00
 */
public abstract class DefaultBaseStoreMethod<T> implements BaseStore {

    private final StoreState<T> STATE_STORE;

    public DefaultBaseStoreMethod(StoreState<T> state) {
        STATE_STORE = state;
    }

    public DefaultBaseStoreMethod(StoreState<T> state, BaseScheduler scheduler, LocalStoreProperty properties) {
        if (properties.isPrune()) {
            scheduler.schedule(state::pruneCache, properties.getDelay());
        }
        STATE_STORE = state;
    }

    public DefaultBaseStoreMethod(StoreState<T> state, BaseScheduler scheduler, long delay) {
        scheduler.schedule(state::pruneCache, delay);
        STATE_STORE = state;
    }

    /**
     * 获取存储器
     *
     * @return 存储器
     */
    protected StoreState<T> getStoreState() {
        return STATE_STORE;
    }

    /**
     * 设置超时时间
     *
     * @param name     唯一key
     * @param duration 指定缓存过期时间
     */
    @Override
    public void expire(String name, Duration duration) {
        getStoreState().expire(buildKey(name), duration);
    }

    /**
     * 是否存在值
     *
     * @param name 保存的name
     * @return 是否存在
     */
    @Override
    public boolean contains(String name) {
        return getStoreState().contains(buildKey(name));
    }

    /**
     * 删除值
     *
     * @param name 保存的name
     */
    @Override
    public void remove(String name) {
        getStoreState().remove(buildKey(name));
    }

    /**
     * 匹配key
     *
     * @param pattern 匹配规则
     * @return keyList
     */
    @Override
    public Set<String> pattern(String pattern) {
        // todo
        return Set.of();
    }

}
